
import 'package:self32/event/write_event.dart';

import '../event/set_eas_event.dart';
import '../main.dart';
import 'socket.dart';

enum Mode { reader, identify, inventoryHfRfid,borrowBook,returnBook,none }


class SocketManager{

  late SocketManager manager;

  SocketManager getManager(){
    return manager;
  }

  factory SocketManager() => _singleton;

  static final SocketManager _singleton = SocketManager._internal();

  SocketManager._internal();

  Mode? mode;
  // String? uid;
  String? no;
  bool? isBorrow;

  setMode(Mode mode){
    this.mode = mode;
  }

  setModeAndStart(Mode mode,{String uid = '', String no = '', bool isBorrow = true}){
    this.mode = mode;
    // this.uid = uid;
    // this.no = no;
    this.isBorrow = isBorrow;
    if(mode == Mode.reader){
      socketHelper.add(m1Inventory());
    }
    if(mode == Mode.identify){
      socketHelper.add(icrInventory());
    }
    if(mode == Mode.inventoryHfRfid){
      if(settingEntity.isUltra!){
        socketHelper.add(inventoryUhfRfid());
      }else{
        socketHelper.add(inventoryHfRfid());
      }
    }
    // if(mode == Mode.borrowBook || mode == Mode.returnBook){
    //   socketHelper.add(setEas(uid,no, isBorrow));
    // }
  }

  start(){
    if(mode == Mode.reader){
      socketHelper.add(m1Inventory());
    }
    if(mode == Mode.identify){
      socketHelper.add(icrInventory());
    }
    if(mode == Mode.inventoryHfRfid){
      if(settingEntity.isUltra!){
        socketHelper.add(inventoryUhfRfid());
      }else{
        socketHelper.add(inventoryHfRfid());
      }
    }
  }

  afi(uid,no){
    socketHelper.add(setAfi(uid,no, isBorrow==true?0xC2:0x07));
  }

  hfEasSuccess(uid,no){
    eventFactory.fire(SetEasEvent(true,uid,no));
  }

  fail(uid,no){
    eventFactory.fire(SetEasEvent(false,uid,no));
  }

  uhfEas(result){
    eventFactory.fire(WriteEvent(result,no));
  }


  eas(uid,no,isBorrow){
    this.no = no;
    this.isBorrow = isBorrow;
    if(settingEntity.isUltra!){
      String rule = settingEntity.analysisBook??'xy';
      if(rule == 'hfh'){
        socketHelper.add(write(uid.replaceRange(0, 4, isBorrow?'0000':'0101'), uid));
      }else{
        socketHelper.add(write(uid.replaceRange(uid.length-2, uid.length, isBorrow?'C2':'07'), uid));

      }
    }else{
      socketHelper.add(setEas(uid, no, isBorrow));
    }
  }



}